package com.cskaoyan.maven.jdbc.util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @ClassName JdbcUtil
 * @Description: TODO
 * @Author 远志 zhangsong@cskaoyan.onaliyun.com
 * @Date 2023/2/8 17:16
 * @Version V1.0
 **/
public class JdbcUtil {

    public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException {
        //获取到加载当前类的类加载器
        ClassLoader classLoader = JdbcUtil.class.getClassLoader();
        InputStream inputStream = classLoader.getResourceAsStream("jdbc.properties");
        Properties properties = new Properties();
        //需要读取properties配置文件的输入流
        //文件位于resources目录----位于classpath-----使用类加载器来获取
        properties.load(inputStream);
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");
        String driver = properties.getProperty("driver");
        Class.forName(driver);
        return DriverManager.getConnection(url, username, password);
    }

    //编写了一个关闭的方法。如果不为null，则关闭
    public static void release(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
        if(connection != null){
            connection.close();
        }
        if(statement != null){
            statement.close();
        }
        if(resultSet != null){
            resultSet.close();
        }
    }
}
